/**
 * Created by sunxiaojun on 2017/11/16.
 */
define([
  './themes/lang/' + window.YUFP_SYS_CONFIG.language + '/pages/content/systemManager/orgInfoManager/orgInfoManager.js',
  './custom/widgets/js/yufpOrgTree.js',
  './custom/widgets/js/yufpExtTree.js'
], function (require, exports) {
  yufp.lookup.reg('DATA_STS,SYS_TYPE,FINCAL_ORG');
  // 自定义字典（金融机构）
  var instuOptions = [];
  // page加载完成后调用ready方法
  exports.ready = function (hashCode, data, cite) {
    var stsKeyValue = null;
    yufp.custom.vue({
      el: '#orgInfo',
      data: function () {
        var em = this;
        return {
          formdata: {},
          heightOrg: yufp.custom.viewSize().height - 152,
          createButton: !yufp.session.checkCtrl('addOrg'), // 新增按钮控制
          editButton: !yufp.session.checkCtrl('editOrg'), // 修改按钮控制
          deleteButton: !yufp.session.checkCtrl('deleteOrg'), // 删除按钮控制
          useButton: !yufp.session.checkCtrl('useOrg'), // 启用按钮控制
          unuseButton: !yufp.session.checkCtrl('unuseOrg'), // 停用按钮控制

          treeUrl: backend.appOcaService + '/api/adminsmorg/orgtreequery',
          dataRoot: {
            orgId: yufp.session.org.id,
            orgName: yufp.session.org.name,
            orgLevel: yufp.session.org.details.orgLevel,
            instuId: yufp.session.instu.id
          },
          mainGrid: {
            query: {
              orgCode: '',
              orgName: '',
              unitOrgId: '',
              orgSts: ''
            },
            height: yufp.custom.viewSize().height - 150,
            checkbox: true,
            dataUrl: backend.appOcaService + '/api/adminsmorg/querypage',
            paging: {
              page: 1,
              size: 10
            },
            currentRow: null,
            dataParams: {
              condition: JSON.stringify({
                unitOrgId: yufp.session.org.id
              })
            },
            tableColumns: [{
              label: this.$t('orgInfoManager.jgmc'),
              prop: 'orgName',
              width: 150,
              resizable: true,
              template: function () {
                return '<template scope="scope">\
                                <a onclick="return false;" href="javascipt:void(0);" class="underline" style="text-decoration:underline;" @click="_$event(\'custom-detail-click\', scope)">{{ scope.row.orgName }}</a>\
                            </template>';
              }
            },
            {
              label: this.$t('orgInfoManager.jgdm'),
              prop: 'orgCode',
              resizable: true
            },
            {
              label: this.$t('orgInfoManager.jrjgmc'),
              prop: 'instuName',
              resizable: true
            },
            {
              label: this.$t('orgInfoManager.zt'),
              prop: 'orgSts',
              width: 90,
              resizable: true,
              template: function () {
                return '<template scope="scope">\
                <yu-tag type="success" v-if="scope.row.orgSts == \'A\' ">生效</yu-tag>\
                <yu-tag type="warning" v-if="scope.row.orgSts == \'W\' ">待生效</yu-tag>\
                <yu-tag type="danger" v-if="scope.row.orgSts == \'I\' ">失效</yu-tag>\
                </template>';
              } 

            },
            {
              label: this.$t('orgInfoManager.zxbgyh'),
              prop: 'lastChgName',
              resizable: true
            },
            {
              label: this.$t('orgInfoManager.zxbgsj'),
              prop: 'lastChgDt',
              type: 'date',
              resizable: true
            },
            {
              label: this.$t('orgInfoManager.sjjg'),
              prop: 'upOrgName',
              type: 'date',
              resizable: true
            }
            ]
          },
          updateFields: [{
            columnCount: 3,
            fields: [{
              field: 'orgName',
              label: this.$t('orgInfoManager.jgmc'),
              rules: [{
                required: true,
                message: this.$t('orgInfoManager.btx'),
                trigger: 'blur'
              },
              {
                max: 100,
                message: this.$t('orgInfoManager.zdcdbcggzf'),
                trigger: 'blur'
              },
              {
                validator: yufp.validator.speChar,
                message: this.$t('orgInfoManager.srxxbhtszf'),
                trigger: 'blur'
              }
              ]
            },
            {
              field: 'orgCode',
              label: this.$t('orgInfoManager.jgdm'),
              disabled: false,
              rules: [{
                required: true,
                message: this.$t('orgInfoManager.btx'),
                trigger: 'blur'
              },
              {
                max: 100,
                message: this.$t('orgInfoManager.zdcdbcggzf'),
                trigger: 'blur'
              },
              {
                validator: yufp.validator.speChar,
                message: this.$t('orgInfoManager.srxxbhtszf'),
                trigger: 'blur'
              }
              ]
            },
            {
              field: 'upOrgId',
              label: this.$t('orgInfoManager.sjjg'),
              type: 'custom',
              is: 'yufp-org-tree',
              params: {
                dataUrl: backend.appOcaService + '/api/adminsmorg/orgtreequery',
                lazy: true,
                indent: 10,
                needCheckbox: false,
                dataRoot: {
                  orgId: yufp.session.org.id,
                  orgName: yufp.session.org.name,
                  orgLevel: yufp.session.org.details.orgLevel,
                  instuId: yufp.session.instu.id
                },
                dataParams: {
                  orgSts: 'A',
                  lazy: true
                }
              },
              rules: [{
                required: true,
                message: this.$t('orgInfoManager.btx'),
                trigger: 'blur'
              }],
              selectFn: function (code, data, arry) {
                if (arry[0].orgLevel === '') {
                  em.$refs.myform.formModel.orgLevel = 1;
                } else {
                  em.$refs.myform.formModel.orgLevel = parseInt(arry[0].orgLevel) + 1;
                  em.$refs.myform.formModel.instuId = arry[0].instuId;
                  if (arry[0].orgLevel != 1) {
                    em.$refs.myform.switch('instuId', 'disabled', true);
                  } else {
                    em.$refs.myform.switch('instuId', 'disabled', false);
                  }
                }
                em.$refs.myform.switch('orgLevel', 'disabled', true);
              }
            },
            {
              field: 'instuId',
              label: this.$t('orgInfoManager.jrjg'),
              type: 'select',
              options: instuOptions,
              rules: [{
                required: true,
                message: this.$t('orgInfoManager.btx'),
                trigger: 'blur'
              }]
            },
            {
              field: 'orgLevel',
              label: this.$t('orgInfoManager.jgcj'),
              disabled: false,
              rules: [{
                required: true,
                validator: yufp.validator.number,
                message: this.$t('orgInfoManager.btx'),
                trigger: 'blur'
              }]
            },
            {
              field: 'orgSts',
              label: this.$t('orgInfoManager.zt'),
              type: 'select',
              dataCode: 'DATA_STS',
              readonly: true
            }
            ]
          }],
          updateFields2: [{
            columnCount: 3,
            fields: [{
              field: 'zipCde',
              label: this.$t('orgInfoManager.yb'),
              rules: [{
                max: 6,
                message: this.$t('orgInfoManager.ybcc'),
                trigger: 'blur'
              },
              {
                validator: yufp.validator.postcode,
                message: this.$t('orgInfoManager.qsrzqyb'),
                trigger: 'blur'
              }
              ]
            },
            {
              field: 'contUsr',
              label: this.$t('orgInfoManager.lxr'),
              rules: [{
                max: 100,
                message: this.$t('orgInfoManager.zdcdbcggzf'),
                trigger: 'blur'
              }]
            },
            {
              field: 'contTel',
              label: this.$t('orgInfoManager.lxdh'),
              rules: [{
                validator: yufp.validator.mobile,
                message: this.$t('orgInfoManager.qsrzqxx'),
                trigger: 'blur'
              }]
            },
            {
              field: 'lastChgName',
              label: this.$t('orgInfoManager.zxbgyh')
            },
            {
              field: 'lastChgDt',
              label: this.$t('orgInfoManager.zxbgsj')
            }
            ]
          }, {
            columnCount: 1,
            fields: [{
              field: 'orgAddr',
              label: this.$t('orgInfoManager.dz'),
              type: 'textarea',
              rows: 1,
              rules: [{
                max: 200,
                message: this.$t('orgInfoManager.zdcdbcggzf'),
                trigger: 'blur'
              }]
            }]
          }],

          stsOptions: null,
          dialogFormVisible: false,
          nowNode: null, // 当前选中节点数据
          rootId: 'root', // 根节点ID
          rootName: this.$t('orgInfoManager.zzjgs'), // 根节点名称
          orgStore: null,
          orgdata: null,
          dialogStatus: '',
          formDisabled: false,
          dialogDisabled: true,
          activeName: ['1'], // 默认显示name为1的
          textMap: {
            update: this.$t('orgInfoManager.xg'),
            create: this.$t('orgInfoManager.xz'),
            detail: this.$t('orgInfoManager.xq')
          },
          options: instuOptions
        };
      },
      methods: {
        queryMainGridFn: function () {
          var me = this;
          var param = {
            condition: JSON.stringify({
              orgCode: this.mainGrid.query.orgCode ? this.mainGrid.query.orgCode : null,
              orgName: this.mainGrid.query.orgName ? this.mainGrid.query.orgName : null,
              unitOrgId: this.mainGrid.query.unitOrgId ? this.mainGrid.query.unitOrgId : yufp.session.org.id,
              orgSts: this.mainGrid.query.orgSts ? this.mainGrid.query.orgSts : null
            })
          };
          me.$refs.mytable.remoteData(param);
        },
        // 查询金融机构
        queryInstuFn: function () {
          yufp.service.request({
            method: 'GET',
            url: backend.appOcaService + '/api/adminsmorg/getinstuorg',
            callback: function (code, message, response) {
              if (code === 0 && response.code === 0) {
                if (instuOptions.length > 0) {
                  instuOptions.splice(0, instuOptions.length);
                }
                var instu = response.data;
                for (var i = 0; i < instu.length; i++) {
                  var option = {};
                  option.key = instu[i].instuId;
                  option.value = instu[i].instuName;
                  instuOptions.push(option);
                }
              }
            }
          });
        },
        nodeClickFn: function (node, obj, nodeComp) {
          if (node != '') {
            this.nowNode = node;
            this.nowNode.orgLevel = node.orgLevel;
            this.mainGrid.query.unitOrgId = node.orgId;
            this.queryMainGridFn();
          }
        },
        resetTempFn: function () {
          this.$refs.myform.resetFn();
          this.$refs.myform1.resetFn();
        },
        closeDialogFn: function () {
          this.dialogFormVisible = false;
        },
        openCreateFn: function () {
          this.queryInstuFn();
          this.dialogStatus = 'create';
          this.activeName = ['1'];
          this.dialogFormVisible = true;
          this.formDisabled = false;
          this.updateFields2[0].fields[3].hidden = true;
          this.updateFields2[0].fields[4].hidden = true;
          this.$nextTick(function () {
            this.$refs.myform.resetFn();
            this.$refs.myform1.resetFn();
            // this.$refs.myform.$refs.upOrgId[0].$refs.orgTree.remoteData();
            this.$refs.myform.formModel.orgSts = 'A';
            var temp = yufp.clone(this.updateFields[0].fields[3].params);
            temp.dataParams = {
              orgSts: 'A',
              orgId: yufp.session.org.code
            };
            this.updateFields[0].fields[3].params = yufp.clone(temp);
            this.$refs.myform.switch('orgCode', 'disabled', false);
            this.$refs.myform.switch('instuId', 'disabled', false);
            this.$refs.myform.switch('orgLevel', 'disabled', true);
            if (this.nowNode != null) {
              this.$refs.myform.formModel.instuId = this.nowNode.instuId;
              this.$refs.myform.formModel.upOrgId = this.nowNode.orgId;
              if (this.nowNode.orgLevel != 1) {
                this.$refs.myform.switch('instuId', 'disabled', true);
              }
              this.$refs.myform.formModel.orgLevel = parseInt(this.nowNode.orgLevel) + 1;
            }
          });
        },
        openDetailFn: function (row) {
          this.dialogStatus = 'detail';
          this.activeName = ['1', '2'];
          this.queryInstuFn();
          this.formDisabled = true;
          this.dialogFormVisible = true;
          this.formDisabled = true;
          this.updateFields2[0].fields[3].hidden = false;
          this.updateFields2[0].fields[4].hidden = false;
          this.$nextTick(function () {
            this.$refs.myform.resetFn();
            this.$refs.myform1.resetFn();

            yufp.extend(this.$refs.myform.formModel, row.row);
            yufp.extend(this.$refs.myform1.formModel, row.row);
          });
        },
        openEditFn: function (row) {
          if (this.$refs.mytable.selections.length !== 1) {
            this.$message({
              message: this.$t('orgInfoManager.qxzytsj'),
              type: 'warning'
            });
            return false;
          }
          var row = this.$refs.mytable.selections[0];
          if (row.orgSts === 'A') {
            this.$message({
              message: this.$t('orgInfoManager.znxztyhdqydsj'),
              type: 'warning'
            });
            return;
          }
          this.queryInstuFn();
          this.dialogStatus = 'update';
          this.activeName = ['1'];
          this.dialogFormVisible = true;
          this.formDisabled = false;
          this.updateFields2[0].fields[3].hidden = true;
          this.updateFields2[0].fields[4].hidden = true;
          this.$nextTick(function () {
            this.$refs.myform.resetFields();
            this.$refs.myform1.resetFields();
            // this.$refs.myform.$refs.upOrgId[0].$refs.orgTree.remoteData();
            this.$refs.myform.switch('orgCode', 'disabled', true);
            this.$refs.myform.switch('orgLevel', 'disabled', true);
            var temp = yufp.clone(this.updateFields[0].fields[3].params);
            temp.dataParams = {
              orgSts: 'A',
              orgId: yufp.session.org.code
            };
            this.updateFields[0].fields[3].params = yufp.clone(temp);
            if (row.orgLevel != 1) {
              this.$refs.myform.switch('instuId', 'disabled', true);
            } else {
              this.$refs.myform.switch('instuId', 'disabled', true);
            }
            yufp.extend(this.$refs.myform.formModel, row);
            yufp.extend(this.$refs.myform1.formModel, row);
          });
        },
        saveCreateFn: function () {
          var me = this;
          var myform = me.$refs.myform,
            myform1 = me.$refs.myform1;
          myform.validate(function (valid) {
            myform1.validate(function (valid1) {
              if (valid == valid1 && valid == true) {
                var comitData = {
                  contTel: null,
                  contUsr: null,
                  orgAddr: null,
                  zipCde: null
                };
                delete myform.formModel.orgId;
                yufp.extend(comitData, myform.formModel);
                comitData.zipCde = myform1.formModel.zipCde;
                comitData.contUsr = myform1.formModel.contUsr;
                comitData.contTel = myform1.formModel.contTel;
                comitData.orgAddr = myform1.formModel.orgAddr;
                comitData.lastChgUsr = yufp.session.userId;
                yufp.service.request({
                  method: 'POST',
                  url: backend.appOcaService + '/api/adminsmorg/addorginfo',
                  data: comitData,
                  callback: function (code, message, response) {
                    if (response.code == 20100022) {
                      me.$message({
                        message: response.message,
                        type: 'warning'
                      });
                    } else {
                      me.dialogFormVisible = false;
                      me.$message({
                        message: me.$t('orgInfoManager.sjbccg')
                      });
                      me.queryMainGridFn();
                      // me.refreshOrgTree();
                      me.$refs.mytree.remoteData();
                    }
                  }
                });
              } else {
                me.$message({
                  message: me.$t('orgInfoManager.qjcsrxsfhf'),
                  type: 'warning'
                });
                return false;
              }
            });
          });
        },
        saveEditFn: function (form) {
          var me = this;
          var myform = me.$refs.myform,
            myform1 = me.$refs.myform1;
          myform.validate(function (valid) {
            myform1.validate(function (valid1) {
              if (valid == valid1 && valid == true) {
                var comitData = {
                  contTel: null,
                  contUsr: null,
                  orgAddr: null,
                  zipCde: null
                };

                yufp.extend(comitData, myform.formModel);
                comitData.zipCde = myform1.formModel.zipCde;
                comitData.contUsr = myform1.formModel.contUsr;
                comitData.contTel = myform1.formModel.contTel;
                comitData.orgAddr = myform1.formModel.orgAddr;
                comitData.lastChgUsr = yufp.session.userId;
                yufp.service.request({
                  method: 'POST',
                  url: backend.appOcaService + '/api/adminsmorg/update',
                  data: comitData,
                  callback: function (code, message, response) {
                    if (response.data.code === '2') {
                      me.$message({
                        message: response.data.message,
                        type: 'warning'
                      });
                    } else {
                      me.dialogFormVisible = false;
                      me.$message({
                        message: me.$t('orgInfoManager.sjbccg')
                      });
                      me.queryMainGridFn();
                      me.$refs.mytree.remoteData();
                    }
                  }
                });
              } else {
                me.$message({
                  message: me.$t('orgInfoManager.qjcsrxsfhf'),
                  type: 'warning'
                });
                return false;
              }
            });
          });
        },
        useBatchFn: function () { // 批量启用
          var rows = this.$refs.mytable.selections;
          var me = this;
          if (rows.length > 0) {
            var id = '';
            for (var i = 0; i < rows.length; i++) {
              var row = rows[i];
              if (row.orgSts === 'W' || row.orgSts === 'I') {
                id = id + ',' + row.orgId;
              } else {
                this.$message({
                  message: this.$t('orgInfoManager.znxzsxhdsxdsj'),
                  type: 'warning'
                });
                return;
              }
            }
            me.$confirm(me.$t('orgInfoManager.cczjqygsjsfjx'), me.$t('orgInfoManager.ts'), {
              confirmButtonText: me.$t('orgInfoManager.qr'),
              cancelButtonText: me.$t('orgInfoManager.qx'),
              type: 'warning'
            }).then(function () {
              yufp.service.request({
                method: 'POST',
                url: backend.appOcaService + '/api/adminsmorg/usebatch?ids=' + id + '&lastChgUsr=' + yufp.session.userId,
                data: {
                  id: id,
                  lastChgUsr: yufp.session.userId
                },
                callback: function (code, message, response) {
                  me.$message({
                    message: me.$t('orgInfoManager.sjczcg')
                  });
                  me.queryMainGridFn();
                  me.$refs.mytree.remoteData();
                }
              });
            });
          } else {
            me.$message({
              message: me.$t('orgInfoManager.qxxzyqydsj'),
              type: 'warning'
            });
            return;
          }
        },
        unUseBatchFn: function () { // 批量停用
          var rows = this.$refs.mytable.selections;
          var me = this;
          if (rows.length > 0) {
            var id = '';
            for (var i = 0; i < rows.length; i++) {
              var row = rows[i];
              if (row.orgSts === 'A') {
                id = id + ',' + row.orgId;
              } else {
                this.$message({
                  message: this.$t('orgInfoManager.znxzysxdsj'),
                  type: 'warning'
                });
                return;
              }
            }
            me.$confirm(me.$t('orgInfoManager.cczjtygsjsfjx'), me.$t('orgInfoManager.ts'), {
              confirmButtonText: me.$t('orgInfoManager.qr'),
              cancelButtonText: me.$t('orgInfoManager.qx'),
              type: 'warning'
            }).then(function () {
              yufp.service.request({
                method: 'POST',
                url: backend.appOcaService + '/api/adminsmorg/unusebatch?ids=' + id + '&lastChgUsr=' + yufp.session.userId,
                data: {
                  id: id,
                  lastChgUsr: yufp.session.userId
                },
                callback: function (code, message, response) {
                  if (code == 0) {
                    me.$message({
                      message: response.message
                    });
                    me.queryMainGridFn();
                    me.$refs.mytree.remoteData();
                  }
                }
              });
            });
          } else {
            me.$message({
              message: me.$t('orgInfoManager.qxxzytydsj'),
              type: 'warning'
            });
            return;
          }
        },
        deletestFn: function () { // 批量删除
          var rows = this.$refs.mytable.selections;
          var me = this;
          if (rows.length > 0) {
            var id = '';
            for (var i = 0; i < rows.length; i++) {
              var row = rows[i];
              if (row.orgSts === 'W' || row.orgSts === 'I') {
                id = id + ',' + row.orgId;
              } else {
                this.$message({
                  message: this.$t('orgInfoManager.znscsxhdsxdsj'),
                  type: 'warning'
                });
                return;
              }
            }
            me.$confirm(me.$t('orgInfoManager.cczjyjscgsjsfjx'), me.$t('orgInfoManager.ts'), {
              confirmButtonText: me.$t('orgInfoManager.qr'),
              cancelButtonText: me.$t('orgInfoManager.qx'),
              type: 'warning'
            }).then(function () {
              yufp.service.request({
                method: 'POST',
                url: backend.appOcaService + '/api/adminsmorg/deletebatch?ids=' + id,
                data: {
                  ids: id
                },
                callback: function (code, message, response) {
                  me.$message({
                    message: response.message
                  });
                  me.queryMainGridFn();
                  me.$refs.mytree.remoteData();
                }
              });
            });
          } else {
            me.$message({
              message: me.$t('orgInfoManager.qxxzyscdsj'),
              type: 'warning'
            });
            return;
          }
        }

      },
      mounted: function () {
        // this.queryMainGridFn();
        var me = this;
        yufp.lookup.bind('DATA_STS', function (data) {
          me.stsOptions = data;
          stsKeyValue = me.stsOptions.reduce(function (acc, cur) {
            acc[cur.key] = cur.value;
            return acc;
          }, {});
        });
      }

    });
  };

  // 消息处理
  exports.onmessage = function (type, message) {

  };

  // page销毁时触发destroy方法
  exports.destroy = function (id, cite) {

  };
});
